package cn.bugstack.xfg.dev.tech.test;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.ai.document.Document;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.PathResource;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class JGitTest {

    @Resource
    private OllamaChatClient ollamaChatClient;
    @Resource
    private TokenTextSplitter tokenTextSplitter;
    @Resource
    private SimpleVectorStore simpleVectorStore;
    @Resource
    private PgVectorStore pgVectorStore;

    @Test
    public void test() throws Exception {
        String repoURL = "https://gitcode.com/weixin_46532327/big-market.git";
        String username = "weixin_46532327";
        String password = "Wg_vxJuVg5uA7Ej9y5g2Edso";


        String localPath = "./cloned-repo";
        log.info("克隆路径：" + new File(localPath).getAbsolutePath());

        FileUtils.deleteDirectory(new File(localPath));

        Git git = Git.cloneRepository()
                .setURI(repoURL)
                .setDirectory(new File(localPath))
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .call();

        git.close();  }


    @Test
    public void test_file() throws IOException {
        Files.walkFileTree(Paths.get("./cloned-repo"), new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 跳过 .git 目录
                if (file.toString().contains(File.separator + ".git") || file.getFileName().toString().startsWith(".")) {
                    log.info("跳过 Git 或隐藏文件: {}", file);
                    return FileVisitResult.CONTINUE;
                }

                // 可选：跳过非文本文件
                String contentType = Files.probeContentType(file);
                if (contentType == null || !contentType.startsWith("text")) {
                    log.info("跳过非文本文件: {}，类型: {}", file, contentType);
                    return FileVisitResult.CONTINUE;
                }

                log.info("解析文件路径: {}", file);

                try {
                    TikaDocumentReader reader = new TikaDocumentReader(new PathResource(file));
                    List<Document> documents = reader.get();

                    if (documents == null || documents.isEmpty()) {
                        log.warn("解析结果为空，跳过: {}", file);
                        return FileVisitResult.CONTINUE;
                    }

                    List<Document> documentSplitterList = tokenTextSplitter.apply(documents);

                    documents.forEach(doc -> doc.getMetadata().put("knowledge", "group-buy-market-liergou"));
                    documentSplitterList.forEach(doc -> doc.getMetadata().put("knowledge", "group-buy-market-liergou"));

                    pgVectorStore.accept(documentSplitterList);
                } catch (Exception e) {
                    log.error("读取文件失败: {} - {}", file, e.getMessage(), e);
                }

                return FileVisitResult.CONTINUE;
            }
        });

    }

}
